﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Analytics.DataObjects.Networks;
using DiscoveryLogic.Analytics.DataObjects.Rules;
using DiscoveryLogic.Common.Utilities;

namespace DiscoveryLogic.Analytics.BusinessLogic.Clusters
{
    public class NetworkEntityClusterWorker
    {
        private Network _Network;
        private List<EntityClusterRule> _ClusterRules;

        public NetworkEntityClusterWorker(Network network, List<EntityClusterRule> clusterRules)
        {
            this._Network = network;
            this._ClusterRules = clusterRules;
        }

        public void ClusterNetworkOnEntity()
        {
            List<NetworkCluster> clusters=new List<NetworkCluster>();
            foreach(EntityClusterRule clusterRule in this._ClusterRules)
            {
                EntityClusterWorker worker=new EntityClusterWorker(clusterRule);
                List<NetworkCluster> networkClusters=new List<NetworkCluster>();
                List<EntityBase> entities=new List<EntityBase>();
                foreach(EntityBase entity in this._Network.Records)
                {
                    if(entity.EntityType==clusterRule.SrcEntityType)
                        entities.Add(entity);
                }
                worker.ClusterEntities(entities, ref networkClusters);
                foreach(NetworkCluster networkCluster in networkClusters)
                    clusters.Add(networkCluster);
            }

            NetworkCluster.Save(this._Network.NetworkName, clusters);
            this._Network = this.AddLinksForCluster(this._Network);
            this._Network.Save();
        }

        private Network AddLinksForCluster(Network network)
        {
            if (network.Links == null)
                network.Links = new List<Link>();
            List<Link> clusterLinks = new List<Link>();
            foreach (Link link in network.Links)
            {
                if (link.RelationType == LinkType.Cluster)
                    clusterLinks.Add(link);
            }
            if (clusterLinks.Count > 0)
            {
                foreach (Link clusterLink in clusterLinks)
                    network.Links.Remove(clusterLink);
            }
            
            return network;
        }
    }
}
